package com.example.drainage.ui.surface

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView

class SurfaceViewHandWriting @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : SurfaceView(context, attrs, defStyleAttr), SurfaceHolder.Callback, Runnable {
    private lateinit var mSurfaceHolder: SurfaceHolder

    //绘图的Canvas
    private var mCanvas: Canvas? = null

    //子线程标志位
    private var mIsDrawing = false

    //画笔
    private val mPaint: Paint = Paint()

    //路径
    private val mPath: Path

    companion object {
        private const val TAG = "SurfaceViewHandWriting::"
    }

    init {
        mPaint.color = Color.BLACK
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = 5f
        mPaint.isAntiAlias = true
        mPath = Path()
        mPath.moveTo(0f, 100f)
        initView()
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        mIsDrawing = true
        Thread(this).start()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        mIsDrawing = false
    }

    override fun run() {
        while (mIsDrawing) {
            val start = System.currentTimeMillis()
            drawSomething()
            val end = System.currentTimeMillis()
            if (end - start < 100) {
                try {
                    Thread.sleep(100 - (end - start))
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x.toInt()
        val y = event.y.toInt()
        when (event.action) {
            MotionEvent.ACTION_DOWN -> mPath.moveTo(x.toFloat(), y.toFloat())
            MotionEvent.ACTION_MOVE -> mPath.lineTo(x.toFloat(), y.toFloat())
            MotionEvent.ACTION_UP -> {
            }
        }
        return true
    }

    /**
     * 初始化View
     */
    private fun initView() {
        mSurfaceHolder = holder
        mSurfaceHolder.addCallback(this)
        isFocusable = true
        keepScreenOn = true
        isFocusableInTouchMode = true
    }

    private fun drawSomething() {
        try {
            //获得canvas对象
            mCanvas = mSurfaceHolder!!.lockCanvas()
            //绘制背景
            mCanvas?.drawColor(Color.WHITE)
            //绘制路径
            mCanvas?.drawPath(mPath, mPaint)
        } catch (e: Exception) {
        } finally {
            if (mCanvas != null) {
                //释放canvas对象并提交画布
                mSurfaceHolder.unlockCanvasAndPost(mCanvas)
                mCanvas = null
            }
        }
    }
}